package com.nmgs.util;

import com.nmgs.entity.TomcatManagerResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;

import java.io.File;
import java.net.URL;
import java.net.URLEncoder;

public class TomcatManager {
    private static final String MANAGER_CHARSET = "UTF-8";
    private String username;
    private URL url;
    private String password;
    private String charset;
    private boolean verbose;
    private DefaultHttpClient httpClient;
    private BasicHttpContext localContext;
    /** constructor */
    public TomcatManager(URL url, String username) {
        this(url, username, "");
    }
    public TomcatManager(URL url, String username, String password) {
        this(url, username, password, "ISO-8859-1");
    }
    public TomcatManager(URL url, String username, String password, String charset) {
        this(url, username, password, charset, true);
    }
    public TomcatManager(URL url, String username, String password, String charset, boolean verbose) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.charset = charset;
        this.verbose = verbose;

        // 创建网络请求相关的配置
        PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager();
        poolingClientConnectionManager.setMaxTotal(5);
        this.httpClient = new DefaultHttpClient(poolingClientConnectionManager);
        if (StringUtils.isNotEmpty(username)) {
            Credentials creds = new UsernamePasswordCredentials(username, password);
            String host = url.getHost();
            int port = url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT;
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), creds);
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            authCache.put(targetHost, basicAuth);
            localContext = new BasicHttpContext();
            localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
    }
    /** 根据指定的path部署并启动一个新的应用程序 */
    public TomcatManagerResponse deploy(String path, File war, boolean update) throws Exception {
        StringBuilder buffer = new StringBuilder("/deploy");
        buffer.append("?path=").append(URLEncoder.encode(path, charset));
        if (war != null) {
            buffer.append("&war=").append(URLEncoder.encode(war.toString(), charset));
        }
        if (update) {
            buffer.append("&update=true");
        }
        return invoke(buffer.toString());
    }
    /** 获取所有已部署的web应用程序的上下文路径。格式为path:status:sessions(活动会话数) */
    public TomcatManagerResponse list() throws Exception {
        StringBuilder buffer = new StringBuilder("/list");
        return invoke(buffer.toString());
    }
    /** 获取系统信息和JVM信息 */
    public TomcatManagerResponse serverinfo() throws Exception {
        StringBuilder buffer = new StringBuilder("/serverinfo");
        return invoke(buffer.toString());
    }
    /** 真正发送请求的方法 */
    private TomcatManagerResponse invoke(String path) throws Exception {
        HttpRequestBase httpRequestBase = new HttpGet(url + path);
        HttpResponse response = httpClient.execute(httpRequestBase, localContext);
        int statusCode = response.getStatusLine().getStatusCode();
        switch (statusCode) {
            case HttpStatus.SC_OK: // 200
            case HttpStatus.SC_CREATED: // 201
            case HttpStatus.SC_ACCEPTED: // 202
                break;
            case HttpStatus.SC_MOVED_PERMANENTLY: // 301
            case HttpStatus.SC_MOVED_TEMPORARILY: // 302
            case HttpStatus.SC_SEE_OTHER: // 303
                String redirectUrl = getRedirectUrl(response);
                this.url = new URL(redirectUrl);
                return invoke(path);
        }
        TomcatManagerResponse TomcatManagerResponse=new TomcatManagerResponse();
        TomcatManagerResponse.setStatusCode(response.getStatusLine().getStatusCode());
        TomcatManagerResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());
        TomcatManagerResponse.setHttpResponseBody(IOUtils.toString(response.getEntity().getContent()));
        return TomcatManagerResponse;
    }

    /** 提取重定向URL */
    protected String getRedirectUrl(HttpResponse response) {
        Header locationHeader = response.getFirstHeader("Location");
        String locationField = locationHeader.getValue();
        // is it a relative Location or a full ?
        return locationField.startsWith("http") ? locationField : url.toString() + '/' + locationField;
    }
}